//login.js
//获取应用实例
let api = require('../../utils/api.js');
const app = getApp()

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    userLocation: app.globalData.userLocation,
    hasUserLocation: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    code: ''
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    wx.login({
      success: (res) => {
        this.setData({
          code: res.code
        })
      },
      fail: () => {
        wx.showModal({
          content: '微信登录失败，请检查网络状态',
          showCancel: false
        })
      },
    })
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })

      wx.navigateTo({
        url: '../index/index'
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })

        wx.switchTab({
          url: '../index/index'
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })

          wx.switchTab({
            url: '../index/index'
          })
        }
      })

    }
  },
  getUserLocation: function (e) {
    let vm = this;
  },
  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  phoneLogin: function (e) {
    wx.navigateTo({
      url: 'phonelogin/index',
    })
  },
  showLaw: function (e) {
    // console.log(e.currentTarget.dataset.showtype)
    let index = e.currentTarget.dataset.showtype;
    let url = [];
    url[1] = '../law/service/index';
    url[2] = '../law/privacy/index';
    url[3] = '../law/empower/index';
    wx.navigateTo({
      url: url[index],
    })
  },

  //用户信息和token
  onGetUserInfo: function (e) {
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '未授权您将无法登陆',
        success: function (res) {}
      })
    } else {
      wx.login({
        success: (res) => {
          this.setData({
            code: res.code
          })
        },
        fail: () => {
          wx.hideLoading();

          wx.showModal({
            content: '微信登录失败，请检查网络状态',
            showCancel: false
          })
        },
      })
      let _self = this;
      const code = this.data.code;
      // console.log(e)
      var parentId = parseInt(wx.getStorageSync('PARENT_ID')) || null;
      // console.log('parentId==', parentId)
      wx.showLoading({
        title: '加载中...',
      });
      wx.getUserInfo({
        success: function (result) {
          // console.log(result);
          var token = wx.getStorageSync('TOKEN');
          var param = {
            userType: 2,
            code: _self.data.code,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
            parent: parentId,
            userInfo: result.userInfo
          }
          api._post('/user/wechat/token', param, token).then(res => {
            var data = res.data;
            if (res.code == 200) {
              app.globalData.userId = res.result.userId;
              app.globalData.expireIn = res.result.expireIn;
              app.globalData.token = res.result.token;
              app.globalData.userType = res.result.userType;
              wx.setStorageSync('EXPIREIN', res.result.expireIn)
              wx.setStorageSync('TOKEN', res.result.token)
              wx.setStorageSync('USERID', res.result.userId);
              wx.switchTab({
                url: '../index/index',
              })
              wx.hideLoading();
            } else if (res.code == 20000008) {
              wx.login({
                success: (res) => {
                  wx.showToast({
                    title: '该账号已注册为货主，请使用登录货主端登录',
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            } else if (res.code == 9999100) {
              wx.login({
                success: (res) => {
                  wx.showToast({
                    title: '验证码不正确',
                    icon: 'none',
                    duration: 2000
                  })
                  this.setData({
                    code: res.code,
                  })
                }
              })
            } else {
              wx.login({
                success: (res) => {
                  wx.showToast({
                    title: res.message,
                    icon: 'none',
                    duration: 2000
                  })
                  this.setData({
                    code: res.code,
                  })
                },
                fail: () => {},
              })
            }
          }).catch(() => {
            wx.hideLoading();
          })
        }
      })
    }
  },
})